package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 当前就是未登录状态, 谈不上退出登录!
            resp.sendRedirect("login.html");
            return;
        }


        String blogId = req.getParameter("blogId");
        if(blogId==null){
            //没有blogId说明是一开始登陆的需要查询用户的所有文章

            String username = (String) session.getAttribute("username");
            User user = UserDao.selectByName(username);
            List<Blog> blogs = BlogDao.selectAll(user.getUserId());
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }else{
            Blog blog = BlogDao.selectOne(Integer.parseInt(blogId));
            if (blog == null) {
                // 返回一个 id 为 0 的 blog 对象. 前端再根据这里进行判定.
                blog = new Blog();
            }
            String respJson = objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录! 无法发布博客!sss");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录! 无法发布博客!aaa");
            return;
        }
        req.setCharacterEncoding("utf8");  // 这个操作不要忘, 否则遇到中文可能会乱码
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //构造博客对象！
        Blog blog =new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        BlogDao.insert(blog);
        //重定向
        resp.sendRedirect("blog_list.html");
    }
}
